'use strict';
(function(root, factory) {
	 if (typeof define === 'function' && define.amd) {
        // AMD
        define(factory);
    } else if (typeof exports === 'object') {
        // CMD
        module.exports = factory();
    } else {
        // 浏览器全局变量
        root.Countdown = factory();
    }
})(this, function () {
	var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
    var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;
		
	function diffTime (lastTime,endTime) {
		var nowTime = new Date().getTime();
		if (typeof lastTime === 'object') {
			lastTime = lastTime.getTime();
		}
		if (typeof lastTime === 'string') {
			lastTime = (new Date(Date.parse(lastTime.replace(/-/g, "/")))).getTime();
		}		

		//return lastTime > nowTime ? lastTime - nowTime : 0;
		return endTime > nowTime ? endTime - nowTime : 0;
	}

	
	function Countdown (container, options) {
		if(!container){return;}	
		var requestID = null;	
        var endTime = 0;   		
		endTime	= new Date().getTime()+parseInt(options.lastTime)*1E3;

		var defaults = {
			format: "hh时mm分ss秒",
			lastTime: "2017-04-20"
		};
		this.format = function (time) { /[\u4E00-\u9FA5\uF900-\uFA2D]/
				if(parseInt(time.h)>0){
					return defaults.format.replace(/hh/ig, time.h).replace(/mm/ig, time.m).replace(/ss/ig, time.s);	
				}else if(parseInt(time.h)==0&&parseInt(time.m)>0){
					return defaults.format.replace(/hh[\u4E00-\u9FA5\uF900-\uFA2D]/ig,"").replace(/mm/ig, time.m).replace(/ss/ig, time.s);	
				}else if(parseInt(time.h)==0&&parseInt(time.m)==0&&parseInt(time.s)>0){
					return defaults.format.replace(/hh[\u4E00-\u9FA5\uF900-\uFA2D]/ig,"").replace(/mm[\u4E00-\u9FA5\uF900-\uFA2D]/ig, "").replace(/ss/ig, time.s);	
				}else{
					return '';	
				}
			
		};
	    this.render = function (format) {
			container.innerHTML = format;
		};
		this.update =function(timestamp) { 
			var countTime = diffTime(options.lastTime,endTime)/1000,
				h = Math.floor(countTime/3600),
				m = Math.floor(((countTime-h*3600))/60),
				s = Math.floor(countTime-h*3600-m*60),
				h = (h > 9 ? h : "0" + h),
				m = (m > 9 ? m : "0" + m),
				s = (s > 9 ? s : "0" + s);
				this.render(this.format({h: h, m: m, s: s}));			    
			  if (countTime <= 0) {
				cancelAnimationFrame(requestID);
				if(typeof(options.complete)=="function"){
					options.complete(container);
				}
				return ;
			  }
			  requestAnimationFrame(this.update);
		}.bind(this);
		requestID = requestAnimationFrame(this.update);
	}
	
    return Countdown;

});
